package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lcz
 * @date 2020/4/22.
 * @Description
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
   private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }



    @GetMapping("/findAllCache")
    public String findAllCache() throws JsonProcessingException {
        //1.查询redis缓存
        //2.存在返回
        //3.不存在 ----》mysql数据库查找----》转为json字符串存入redis ---》返回
        String usersStr = "";
        usersStr = (String) redisTemplate.boundValueOps("userAll364").get();
        /*if(null != usersStr && "" !=usersStr){
        }*/
        if(StringUtils.isEmpty(usersStr)){ //不存在
            log.info("-----------从mysql数据库中查找-----------------");
            //不存在 ----》mysql数据库查找----》转为json字符串存入redis ---》返回
            List<User> userList = userService.findAll();
            ObjectMapper objectMapper = new ObjectMapper();
            usersStr = objectMapper.writeValueAsString(userList);
            redisTemplate.boundValueOps("userAll364").set(usersStr);
        }
        return usersStr;
    }
}
